package ipaddress;

import java.net.*;
import java.util.Enumeration;

public class IpAddressDemo {

    public static String getLocalIPv6Address() throws SocketException {
        InetAddress inetAddress = null;

        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        outer:
        //退出多重循环
        while (networkInterfaces.hasMoreElements()) {
            Enumeration<InetAddress> inetAds = networkInterfaces.nextElement().getInetAddresses();
            while (inetAds.hasMoreElements()) {
                inetAddress = inetAds.nextElement();
                //检查此地址是否是IPv6地址以及是否是保留地址
                if (inetAddress instanceof Inet6Address && !isReservedAddr(inetAddress)) {
                    break outer;
                }
            }
        }
        String ipAddr = inetAddress.getHostAddress();
        //过滤网卡
        int index = ipAddr.indexOf('%');
        if (index > 0) {
            ipAddr = ipAddr.substring(0, index);
        }

        return ipAddr;
    }

    //判断是否是保留地址
    private static boolean isReservedAddr(InetAddress inetAddr) {
        if (inetAddr.isAnyLocalAddress() || inetAddr.isLinkLocalAddress() || inetAddr.isLoopbackAddress()) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {

        try {
            InetAddress ipv4_1 = InetAddress.getByName("localhost");
            InetAddress ipv4_2 = InetAddress.getByAddress(new byte[]{127, 0, 0, 1}); //127.0.0.1
            InetAddress ipv4_3 = Inet4Address.getByAddress("localhost", new byte[]{127, 0, 0, 1});
            System.out.println(ipv4_1);
            System.out.println(ipv4_2);
            System.out.println(ipv4_3);

            //获取本机的ipv6的地址。
            System.out.println(getLocalIPv6Address());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
